<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j component-month-picker">
    <picker-view
      v-if="visible"
      :indicator-style="indicatorStyle"
      :value="dateValue"
      class="picker-view"
      @change="bindChange"
    >
      <picker-view-column>
        <view
          v-for="(item, index) in years"
          :key="index"
          class="item"
        >
          {{ item }}年
        </view>
      </picker-view-column>
      <picker-view-column>
        <view
          v-for="(item, index) in months"
          :key="index"
          class="item"
        >
          {{ item }}月
        </view>
      </picker-view-column>
    </picker-view>
  </view>
</template>
<script setup>
import { watch } from 'vue'

import dayjs from 'dayjs'

const emit = defineEmits(['update:modelValue'])

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: 'start'
  },
  // 是否只能选择过去时间
  checkPast: {
    type: Boolean,
    default: false
  }
})
const [
  _years,
  _year,
  _months,
  _month] = (() => {
  const date = new Date()
  const years = []
  const year = date.getFullYear()
  const months = []
  const month = date.getMonth() + 1
  for (let i = 1990; i <= date.getFullYear() + (props.checkPast ? 0 : 10); i++) {
    years.push(i)
  }
  for (let i = 1; i <= (props.checkPast ? month : 12); i++) {
    months.push(i)
  }
  return [
    years,
    year,
    months,
    month
  ]
})()

const years = _years
let year = _year
const months = ref(_months)
let month = _month
const dateValue = reactive([year - 1990, month - 1])
const visible = ref(true)
const indicatorStyle = 'height: 50rpx;'

watch(() => props.modelValue, (val) => {
  if (val && val.length > 6) {
    dateValue[0] = Number(val.substring(0, 4)) - 1990
    dateValue[1] = Number(val.substring(5, 7)) - 1
  }
}, {
  immediate: true
})

const bindChange = (e) => {
  const val = e.detail.value
  year = years[val[0]]
  month = months.value[val[1]]
  // 重新获取月份
  if (props.checkPast) {
    getPastTime()
  }
  let date = dayjs(year + '-' + month, 'YYYY-M')
  date = date.startOf('month').format('YYYY-MM')
  emit('update:modelValue', date)
}
const getPastTime = () => {
  const date = new Date()
  const y = date.getFullYear()
  const m = date.getMonth() + 1

  months.value = []
  for (let i = 1; i <= (+year === y ? m : 12); i++) {
    months.value.push(i)
  }
}

</script>
<style lang="scss" scoped>
.component-month-picker {
  z-index: 9999;
  .picker-view {
  width: 100%;
  height: 310rpx;
  margin-top: 20rpx;
  }
  .item {
    // height: 50rpx;
    line-height: 50rpx;
    align-items: center;
    justify-content: center;
    text-align: center;
  }
}

</style>
